package com.greenyoung.pwiki.uaa.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.greenyoung.pwiki.uaa.entity.UserEntity;
import com.greenyoung.pwiki.uaa.service.UserService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author Mr.Zhao
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    private UserService userService;

    public UserDetailServiceImpl(UserService userService) {
        this.userService = userService;
    }

    /**
     * 根据用户名查询用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        UserEntity userEntity = userService.getOne(queryWrapper);
        //数据脱敏
        String password = userEntity.getPassword();
        userEntity.setPassword("");
        if (userEntity == null) {
            return null;
        }
        //根据id查询用户权限
        Set<String> permissions = userService.findPermissionsByUserId(userEntity.getId());
        //将permissions转成数组
        String[] permissionArray = new String[permissions.size() + 1];
        permissions.toArray(permissionArray);
        permissionArray[permissions.size()] = "p1";
        //将user的全部信息封装成json
        String principal = JSON.toJSONString(userEntity);
        return User.withUsername(principal)
                .password(password)
                .authorities(permissionArray)
                .build();
    }
}
